<!--
 * @Author: gaoyu gy15354315043@163.com
 * @Date: 2024-10-16 09:50:55
 * @LastEditors: gaoyu gy15354315043@163.com
 * @LastEditTime: 2024-11-29 13:39:58
 * @Description: 
 * Copyright (c) 2024-present HBIS Digital Technology Co.,Ltd. All rights reserved. 
-->
<template>
    <DtDialog v-model="visible" title="修改密码" @close="handleClose" @confirm="handleConfirm" :isLoading="isLoading"
        class="uploadPasswordDialog" :append-to-body="true" :size="'small'" :hiddenFullBtn="true">
        <DtForm ref="formRef" v-model="formPassword" :columns="passwordColumns" :rules="rules" :hasFooter="false"
            @submit="handleChangePassword" :hasErrorTip="false">
            <template #plus-field-password>
                <el-input :key="data.passwordType" ref="password" v-model.trim="formPassword.password"
                    :type="data.passwordType" placeholder="请输入密码" name="password" tabindex="2" maxlength="20"
                    auto-complete="off">
                    <template #suffix>
                        <span class="svg-container show-pwd" @click="showPwd('password')">
                            <svg-icon :icon-class="data.passwordType === 'password' ? 'hide_login' : 'vector_login'"
                                class="el-input__icon " />
                        </span>
                    </template>
                </el-input>
            </template>
            <template #plus-field-newPassword>
                <el-input :key="data.newPasswordType" ref="newPassword" v-model.trim="formPassword.newPassword"
                    :type="data.newPasswordType" placeholder="请输入新密码" name="newPassword" tabindex="2" maxlength="20"
                    auto-complete="off">
                    <template #suffix>
                        <span class="svg-container show-pwd" @click="showPwd('newPassword')">
                            <svg-icon :icon-class="data.newPasswordType === 'password' ? 'hide_login' : 'vector_login'"
                                class="el-input__icon " />
                        </span>
                    </template>
                </el-input>
            </template>
            <template #plus-field-repeatPassword>
                <el-input :key="data.repeatPasswordType" ref="repeatPassword" v-model.trim="formPassword.repeatPassword"
                    :type="data.repeatPasswordType" placeholder="请输入确认密码" name="repeatPassword" tabindex="2"
                    maxlength="20" auto-complete="off">
                    <template #suffix>
                        <span class="svg-container show-pwd" @click="showPwd('repeatPassword')">
                            <svg-icon
                                :icon-class="data.repeatPasswordType === 'password' ? 'hide_login' : 'vector_login'"
                                class="el-input__icon " />
                        </span>
                    </template>
                </el-input>
            </template>
        </DtForm>
    </DtDialog>
</template>
<script lang="ts" setup>
import { editPassword, getPwdRole } from '../../api/update-password/index'
import { useUserStoreHook } from '@/framework/store/modules/user';
import { encryption } from '@/framework/utils/cryptojs/index'
import { ElMessageBox } from 'element-plus'
import { getCurrentInstance } from 'vue'
import { DtColumn } from 'hbisdt-design'
const vm = getCurrentInstance()!
const { useDialog } = vm.appContext.config.globalProperties
const { visible, closeDialog, openDialog, isLoading, submitLoading, cancelLoading } = useDialog()
const formRef = ref()
const password = ref()
const newPassword = ref()
const repeatPassword = ref()
const userStore = useUserStoreHook();
interface PasswordFormType {
    password?: string;
    newPassword?: string;
    repeatPassword?: string
}
let formPassword = ref<PasswordFormType>({
    password: '',
    newPassword: '',
    repeatPassword: ''
})
const passwordColumns: DtColumn[] = [
    {
        label: '旧密码',
        prop: 'password',
    },
    {
        label: '新密码',
        prop: 'newPassword',
    },
    {
        label: '确认密码',
        prop: 'repeatPassword',
    },
]
interface PwdRoleType {
    pwdRegularExpression: string;
    pwdRgDescribe: string;
}
interface dataType {
    pwdrole: PwdRoleType;
    pwdreg: RegExp;
    pwdregcon: string;
    passwordType: string;
    newPasswordType: string;
    repeatPasswordType: string;
    type: string;
}
const INPUT_TYPES = 'password'
const data = reactive<Partial<dataType>>({
    pwdrole: {
        pwdRegularExpression: '',
        pwdRgDescribe: ''
    },
    pwdreg: /^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/,
    pwdregcon: '',
    passwordType: INPUT_TYPES,
    newPasswordType: INPUT_TYPES,
    repeatPasswordType: INPUT_TYPES
})
const rules = {
    password: { required: true, message: '请输入旧登录密码', trigger: 'change' },
    newPassword: {
        required: true,
        validator: (rule: unknown, value: string, callback: (res?: Error | string) => void): void => {
            if (!value) {
                callback('请输入新登录密码')
            } else if (data.pwdreg?.test(value) === false) {
                callback(data.pwdregcon)
            }
            else {
                callback()
            }
        },
        trigger: 'change'
    },
    repeatPassword: {
        required: true,
        validator: (rule: unknown, value: string, callback: (res?: Error | string) => void): void => {
            if (!value) {
                callback('请再次输入新登录密码')
            } else if (value !== formPassword.value.newPassword) {
                callback('密码两次不一致')
            }
            else {
                callback()
            }
        },
        trigger: 'change'
    }
}
/**
 * @description:  关闭弹窗
 * @return {*}
 */
function handleClose(): void {
    closeDialog()
    formPassword = ref<PasswordFormType>({})
}
/**
 * @description:  保存表单
 * @return {*}
 */
function handleConfirm(): void {
    if (!formRef.value) return
    formRef.value.handleSubmit()
}
/**
 * @description:  修改密码
 * @return {*}
 */
async function handleChangePassword(): Promise<void> {
    submitLoading()
    try {
        const tempData = encryption<PasswordFormType>({
            data: formPassword.value
        })
        await editPassword(tempData)
        cancelLoading()
        handleClose()
        ElMessageBox.alert('您的密码已修改，请重新登录。', '提示', {
            type: 'warning',
            confirmButtonText: '确定',
            callback: () => {
                userStore.resetToken()
                location.reload()
            }
        })
    } catch (error) {
        cancelLoading()
    }
}
/**
 * @description:  获取密码策略
 * @return {*}
 */
function getPwdConfig(): void {
    getPwdRole().then(res => {
        data.pwdrole = res.data
        data.pwdreg = new RegExp(data.pwdrole.pwdRegularExpression)
        data.pwdregcon = data.pwdrole.pwdRgDescribe
    })
}
/**
 * @description: 点击密码图标
 * @param {*} i
 * @return {*}
 */
function showPwd(type: string): void {
    switch (type) {
        case 'password':
            data.passwordType = data.passwordType == 'password' ? '' : 'password'
            break;
        case 'newPassword':
            data.newPasswordType = data.newPasswordType == 'password' ? '' : 'password'
            break;
        case 'repeatPassword':
            data.repeatPasswordType = data.repeatPasswordType == 'password' ? '' : 'password'
            break;
        default:
            break;
    }
    const selectRef = type == 'password' ? password : type == 'newPassword' ? newPassword : repeatPassword
    nextTick(() => {
        (selectRef.value).focus()
    })
}
defineExpose({
    openDialog,
    getPwdConfig
})
</script>
<style lang="scss" scoped>
$dark_gray: #889aa4;

.uploadPasswordDialog {
    .el-input__icon {
        font-size: 16px;
        margin: 0;
    }

    .svg-container {
        display: inline-block;
        color: $dark_gray;
        line-height: 13px;
        vertical-align: middle;
    }

    .show-pwd {
        color: $dark_gray;
        font-size: 16px;
        cursor: pointer;
        user-select: none;

    }
}
</style>
